package com.matt.service.courseV2.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dotflat.util.UuidUtil;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.page.PagerQuery;
import com.matt.domain.Children;
import com.matt.domain.courseV2.*;
import com.matt.domain.courseV2.po.ChildrenMonthBodyPO;
import com.matt.domain.courseV2.po.ChildrenMonthInfoPO;
import com.matt.domain.courseV2.po.DevelopDetailsPO;
import com.matt.domain.courseV2.po.GrowthObservationCountPO;
import com.matt.domain.courseV2.vo.ChildrenMonthRecordVO;
import com.matt.domain.rel.RelClassesChildren;
import com.matt.foundation.constant.FeedsConstant;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.CopyUtils;
import com.matt.foundation.utils.DateUtil;
import com.matt.repository.ChildrenRepository;
import com.matt.repository.ClassesRepository;
import com.matt.repository.base.BaseNativeSqlRepository;
import com.matt.repository.base.ChildStatureRepository;
import com.matt.repository.base.ChildrenMonthRecordV2Repository;
import com.matt.repository.courseV2.*;
import com.matt.repository.rel.RelClassesChildrenRepository;
import com.matt.service.FeedsService;
import com.matt.service.courseV2.ChildrenMonthRecordService;
import com.matt.service.courseV2.DevelopReviewService;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ChildrenMonthRecordServiceImpl implements ChildrenMonthRecordService {


    @Autowired
    private BaseNativeSqlRepository baseNativeSqlRepository;

    @Autowired
    private ChildrenRepository childrenRepository;

    @Autowired
    private ClassesRepository classesRepository;

    @Autowired
    protected MemVerificationCache cache;

    @Autowired
    protected ChildrenMonthTemplateRepository childrenMonthTemplateRepository;

    @Autowired
    protected ChildrenMonthRecordRepository childrenMonthRecordRepository;

    @Autowired
    protected ChildrenMonthRecordV2Repository childrenMonthRecordV2Repository;

    @Autowired
    private GrowthObservationRecordRepository growthObservationRecordRepository;

    @Autowired
    private DevelopReviewRepository developReviewRepository;

    @Autowired
    private DevelopReviewService developReviewService;

    @Autowired
    private DevelopUserRepository developUserRepository;

    @Autowired
    private FeedsService feedsService;

    @Autowired
    private RelClassesChildrenRepository relClassesChildrenRepository;

    @Autowired
    private ChildStatureRepository childStatureRepository;

    @Override
    public ChildrenMonthTemplate getChildrenMonthTemplate(String templateId) {
        return childrenMonthTemplateRepository.getOne(templateId);
    }

    @Override
    public Page<ChildrenMonthTemplate> getChildrenMonthTemplateList(PagerQuery pagerQuery) {
        Pageable pageable = PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize());
        return childrenMonthTemplateRepository.findAll(pageable);
    }

    @Override
    public ChildrenMonthTemplate add(ChildrenMonthTemplate childrenMonthTemplate) {
        return childrenMonthTemplateRepository.save(childrenMonthTemplate);
    }


    @Override
    public ChildrenMonthInfoPO childrenInfo(String childrenId, Integer month) {

        ChildrenMonthInfoPO po = new ChildrenMonthInfoPO();
        Children children = childrenRepository.getOne(childrenId);
        if (Objects.isNull(children)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "学生不存在！");
        }

        if (Objects.isNull(month)){
            try {
                Integer monthInterval = DateUtil.betweenMonths(DateUtil.millisToDateTime(new Date().getTime(), "yyyy-MM-dd"), DateUtil.formatDayToStr(children.getBirthday()));//月龄
                month= monthInterval;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        //学生信息
        po.setChildren(children);
        //儿心量表
        GrowthObservationRecord growthObservationRecord = growthObservationRecordRepository.findByChildrenIdAndMonthAge(childrenId, month);
        if (Objects.nonNull(growthObservationRecord)) {
            po.setLabel(growthObservationRecord.getLabel());
            po.setContent(growthObservationRecord.getContent());
        }
        //月核检结果
        List<DevelopReview> developReviews = developReviewRepository.findByMonthOrderByOrderNumAsc(month);

        List<DevelopDetailsPO> developDetailsList = new ArrayList<>();
        if (Objects.nonNull(developReviews)) {
            if (developReviews.size()>0){
                for (int i = 0; i <developReviews.size() ; i++) {
                    DevelopUser developUser = developUserRepository.findAllByChildrenIdAndDevelopId(childrenId, developReviews.get(i).getId());

                    if (Objects.nonNull(developUser)) {
                        DevelopDetailsPO developDetailsPO = developReviewService.childrenDetails(developUser.getId());
                        developDetailsList.add(developDetailsPO);
                    }
                }
            }
        }
        po.setDevelopDetailsList(developDetailsList);
        //获取身体三围集合
        po.setChildrenMonthBodyList(getChildrenMonthBody(childrenId,children.getBirthday()));
        int m = month-1;
        //当月龄大于学生当前月龄取当前月龄
        if (month>po.getChildrenMonthBodyList().size()){
            m = po.getChildrenMonthBodyList().size()-1;
            month = po.getChildrenMonthBodyList().size();
        }

        //基础信息
        po.setChildrenMonth(month);
        po.setChildrenId(children.getId());
        po.setChildrenName(children.getName());
        //当月最新三围信息
        po.setHeader(po.getChildrenMonthBodyList().get(m).getHeader());
        po.setHeight(po.getChildrenMonthBodyList().get(m).getHeight());
        po.setWeight(po.getChildrenMonthBodyList().get(m).getWeight());

        List<Object[]> objects = childrenMonthRecordV2Repository.findChildIdAvg(childrenId,DateUtil.addMonth(children.getBirthday(),month));

        for (int i = 0; i < objects.size(); i++) {
            po.setSleepAvg(String.valueOf(new BigDecimal(objects.get(i)[0].toString()).intValue()));
            po.setSleepCount(String.valueOf(new BigDecimal(objects.get(i)[2].toString()).intValue()));
            po.setSleepAmount(String.valueOf(new BigDecimal(objects.get(i)[1].toString()).intValue()));
        }

        List<Object[]> objects1 = childrenMonthRecordV2Repository.findChildIdByFoodCount(childrenId,DateUtil.addMonth(children.getBirthday(),month));

        for (int i = 0; i < objects1.size(); i++) {
            po.setDiet( objects1.get(i)[0].toString());
            if (Objects.nonNull(objects1.get(i)[0].toString()) && !StringUtils.equals(objects1.get(i)[0].toString()," ")){
                List<Object[]> objects2 = childrenMonthRecordV2Repository.findChildIdByDietAmountAndDietCount(childrenId,DateUtil.addMonth(children.getBirthday(),month),objects1.get(0)[0].toString());
                for (int j = 0; j < objects2.size(); j++) {
                    po.setDietAmount( String.valueOf(new BigDecimal(objects2.get(i)[0].toString()).intValue()));
                    po.setDietCount(String.valueOf(new BigDecimal(objects2.get(i)[1].toString()).intValue()));
                }
            }
        }
        return po;
    }

//    List<ChildrenMonthBodyPO>  getChildrenMonthBody(String childrenId) {
//        return childStatureRepository.findChildStature(childrenId);
//    }


    List<ChildrenMonthBodyPO>  getChildrenMonthBody(String childrenId, Date birthday) {

        List<String> list = DateUtil.getMonthBetweenDate(birthday, new Date());

        List<Object[]> objects = childrenMonthRecordV2Repository.findChildrenMonthBody(childrenId);
        List<ChildrenMonthBodyPO> childrenMonthBodyList = new ArrayList<>();

         String weight ="0";
         String height ="0";
         String header ="0";
        for (int i = 1; i < list.size(); i++) {
            ChildrenMonthBodyPO childrenMonthBodyPO = new ChildrenMonthBodyPO();
            childrenMonthBodyPO.setChildrenMonth(i);
            childrenMonthBodyPO.setHeader(header);
            childrenMonthBodyPO.setWeight(weight);
            childrenMonthBodyPO.setHeight(height);
            for (int j = 0; j < objects.size(); j++) {
                if (StringUtils.equals(objects.get(j)[0].toString(),list.get(i))){
                    if (!StringUtils.equals(objects.get(j)[2].toString(),"0") && !StringUtils.equals(objects.get(j)[1].toString()," ")){
                        childrenMonthBodyPO.setWeight(objects.get(j)[2].toString());
                        weight= objects.get(j)[2].toString();
                    }
                    if ((!StringUtils.equals(objects.get(j)[3].toString(),"0") && !StringUtils.equals(objects.get(j)[3].toString()," "))
                    ){
                        childrenMonthBodyPO.setHeight(objects.get(j)[3].toString());
                        height= objects.get(j)[3].toString();
                    }

                    if ((!StringUtils.equals(objects.get(j)[4].toString(),"0") && !StringUtils.equals(objects.get(j)[4].toString()," "))
                    ){
                        childrenMonthBodyPO.setHeader(objects.get(j)[4].toString());
                        header= objects.get(j)[4].toString();
                    }
                }
            }
            childrenMonthBodyList.add(childrenMonthBodyPO);
        }
        return childrenMonthBodyList;
    }


    @Override
    public ChildrenMonthRecord addRecord(String ticket ,ChildrenMonthRecord childrenMonthRecord) {

        StaffDTO staffDTO = cache.getStaff(ticket);
        ChildrenMonthRecord childrenMonthRecord1 = childrenMonthRecordRepository.findByChildrenIdAndChildrenMonthOrderByCreatedAsc(childrenMonthRecord.getChildrenId(),childrenMonthRecord.getChildrenMonth());
        if (Objects.nonNull(childrenMonthRecord1)){
            childrenMonthRecord.setId(childrenMonthRecord1.getId());
        }
        childrenMonthRecord.setCreatedBy(staffDTO.getId());
        childrenMonthRecord.setCreatedName(staffDTO.getRealName());
        childrenMonthRecord.setAreaId(staffDTO.getAreaId());
        childrenMonthRecord = childrenMonthRecordRepository.save(childrenMonthRecord);

        Children children  = childrenRepository.getOne(childrenMonthRecord.getChildrenId());
        feedsService.save(staffDTO.getId(), childrenMonthRecord.getChildrenId(), staffDTO.getAreaId(), "", FeedsConstant.MONTHLY_REPORT, children.getName()+"的"+childrenMonthRecord.getChildrenMonth()+"月报", "","", "", childrenMonthRecord.getId());

        return childrenMonthRecordRepository.save(childrenMonthRecord);
    }

    @Override
    public ChildrenMonthRecord get(String childrenId, Integer month) {

        ChildrenMonthRecord byChildrenIdAndChildrenMonth = childrenMonthRecordRepository.findByChildrenIdAndChildrenMonthOrderByCreatedAsc(childrenId, month);
        Children children = childrenRepository.getOne(childrenId);
        if(null!=byChildrenIdAndChildrenMonth && null!=children){
            // 使用Fastjson替换content中的值
            try {
                JSONObject jsonContent = JSON.parseObject(byChildrenIdAndChildrenMonth.getContent());  // 解析为JSON对象
                if(null!=children.getWeight()){
                    jsonContent.put("weight", children.getWeight());  // 替换weight值
                }
                if(null!=children.getHeight()){
                    jsonContent.put("height", children.getHeight());  // 替换height值
                }
                byChildrenIdAndChildrenMonth.setContent(jsonContent.toJSONString());  // 更新为修改后的JSON字符串
            } catch (Exception e) {
                // 解析失败时保留原始content
                e.printStackTrace();  // 可选：记录错误日志
            }
        }

        return byChildrenIdAndChildrenMonth;
    }

    @Override
    public ChildrenMonthRecord getId(String id) {
        return childrenMonthRecordRepository.getOne(id);
    }

    @Override
    public Page<ChildrenMonthRecordVO> getList(String ticket, String childrenId, Integer month, String classId, String name, PagerQuery pagerQuery) {
        StaffDTO staffDTO = cache.getStaff(ticket);
//        ChildrenMonthRecord childrenMonthRecord = childrenMonthRecordRepository.findByChildrenIdAndChildrenMonth(childrenId,month);
//        if (Objects.isNull(childrenMonthRecord)){
//            return  new PageImpl<>(new ArrayList<>(), PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize()), 0);
//        }
        Page<ChildrenMonthRecordVO> page = childrenMonthRecordV2Repository.getList(staffDTO,childrenId,month,classId,name,pagerQuery);

        return  page;
    }

    @Override
    public Page<ChildrenMonthRecordVO> getList1(String areaId, String childrenId, Integer month, String classId, String name, PagerQuery pagerQuery) {
        Page<ChildrenMonthRecordVO> page = childrenMonthRecordV2Repository.getList1(areaId,childrenId,month,classId,name,pagerQuery);

        return  page;
    }

    @Override
    public ChildrenMonthRecord update(ChildrenMonthRecord childrenMonthRecord) {
        return childrenMonthRecordRepository.save(childrenMonthRecord);
    }
}
